const config = require('../../config');
const app = getApp()

Page({
  data: {
    defaultGroup: [],
    crGrouplist: [],
    isnulldata: false,
    pageindex: 1,
    pageindex2: 1,
    showpage: 0,
    grouptypetab: false,
    sysPay: 2,
    InStatus: 0,
    showsearch: false,
    keyword: "输入关键字",
    wxInfo: true,    
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
  },
  bindGetUserInfo: function (e) {
    var self = this;
    app.getWxInfo((err, wxInfo) => {
      if (!err) {
        self.setData({
          wxInfo: wxInfo
        });
      }
    });
  },
  onLoad: function () {
    if (!app.globalData.wxInfo) {
      var self = this;
      app.getWxInfo((err, wxInfo) => {
        if (err) {
          console.log(err)
          self.setData({
            wxInfo: false
          });
        }
      });
    }

    this.loadlist();
  },
  loadlist: function () {
    this.setData({
      isloadingdata: true
    });

    var defaultGroup = this.data.defaultGroup;
    var _this = this;
    wx.request({
      url: config.grouplistUrl,
      data: {
        ptType: 1,
        xaParams: encodeURIComponent(_this.data.keyword != '输入关键字'?_this.data.keyword:''),
        currentPageNum: _this.data.pageindex,
        pageNum: 10,
        orderTime: 2
      },
      success: function (res) {
        // console.log(res.data);
        if (res.data && res.data.data) {
          _this.setData({
            defaultGroup: defaultGroup.concat(res.data.data.list),
            isloadingdata: false
          });
          if (res.data.data.totalPageNum == _this.data.pageindex) {
            _this.setData({
              isnulldata: true,
            });
          }
          _this.listsettinggroup();
        } else {
          wx.showToast({
            icon: 'none',
            title: '网络异常',
          })
        }
      }
    })
  },
  tabpage: function(event){
    var tab = event.currentTarget.dataset.tab;
    this.setData({
      showpage: tab
    });
    if(tab == 1){
      this.loadgrouplist();
    }else{
      if(!this.data.defaultGroup.length){
        this.loadlist();
      }
    }
  },
  loadgrouplist: function(){
    this.setData({
      isloadingdata: true
    });

    var crGrouplist = this.data.crGrouplist;
    var _this = this;
    wx.request({
      url: config.ctgrouplistUrl,
      data: {
        status: 1,
        xaParams: encodeURIComponent(_this.data.keyword != '输入关键字'?_this.data.keyword:''),
        currentPageNum: _this.data.pageindex2,
        pageNum: 10,
        payNum: 1
      },
      success: function (res) {
        console.log(res.data);
        if (res.data && res.data.data) {
          _this.setData({
            crGrouplist: crGrouplist.concat(res.data.data.list),
            isloadingdata: false
          });
          if (res.data.data.totalPageNum == _this.data.pageindex) {
            _this.setData({
              isnulldata2: true,
            });
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: '网络异常',
          })
        }
      }
    })
  },
  onReachBottom: function () {
    if (this.data.showpage == 0){
      if (this.data.isloadingdata || this.data.isnulldata) {
        return false;
      }
      var page = this.data.pageindex + 1;
      this.setData({
        pageindex: page
      });
      this.loadlist();
    } else if (this.data.showpage == 1){
      if (this.data.isloadingdata || this.data.isnulldata2) {
        return false;
      }
      var page = this.data.pageindex2 + 1;
      this.setData({
        pageindex2: page
      });
      this.loadgrouplist();
    }
  },
  listsettinggroup: function(){
    var list = this.data.defaultGroup;
    
    for(var i = 0; i < list.length; i++){
      var item = list[i];
      if(i == 0){

      }else{
        var parent = list[i - 1];
        if (item.institutionCode == parent.institutionCode){
          if(i == 1){
            parent.itemdata = [i];
            parent.isgroupone = true;
            item.hideitem = true;
          }else{
            if (parent.hideitem){
              for(var j = i-2; j>0; j--){
                var parents = list[j];
                if (item.institutionCode == parents.institutionCode && parents.isgroupone){
                  item.hideitem = true;
                  parents.itemdata.push(i);
                  break;
                }
              }
            }else{
              parent.isgroupone = true;
              parent.itemdata = [i];
              item.hideitem = true;
            }
          }
        }
      }      
    }
    this.setData({
      defaultGroup: list
    });
  },
  showhidegroup: function (event){
    var index = event.currentTarget.dataset.index;
    var list = this.data.defaultGroup;
    var item = list[index];
    // console.log(index);
    if (item.showgroupitem){
      item.showgroupitem = false;
      for (var i =0; i< item.itemdata.length; i++){
        var iindex = item.itemdata[i];
        list[iindex].hideitem = true;
      }
    }else{
      item.showgroupitem = true;
      for (var i = 0; i < item.itemdata.length; i++) {
        var iindex = item.itemdata[i];
        list[iindex].hideitem = false;
      }
    }
    this.setData({
      defaultGroup: list
    });
  },
  ktgrouptype: function(event){
    var index = event.currentTarget.dataset.index;
    this.setData({
      grouptypetab: true,
      xdindex: index
    });
  },
  hidegrouptab: function(){
    this.setData({
      grouptypetab: false
    });
  },
  grouptypeswtch: function (event){
    var types = event.currentTarget.dataset.type;
    this.groupaddrequert(types)
  },
  groupaddrequert: function (types){
    wx.showLoading();
    var item = this.data.defaultGroup[this.data.xdindex];
    console.log(item);
    var self = this;
    var requerData = {
      styoeCode: item.code,
      Initiator: app.globalData.userInfo.openId,
      InStatus: types,
      pic: app.globalData.wxInfo.avatarUrl,
    }
    if (types == 1 || item.ptInitiatorRatio == item.ptPrice){
      requerData.sysPay = 2
    }
    //请求创建团购
    wx.request({
      header: {
        token: config.token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: requerData,
      method: "POST",
      url: config.addgroupUrl,
      success: res => {
        wx.hideLoading();
        if (res && res.data) {
          self.setData({
            grouptypetab: false
          });

          wx.showToast({
            icon: "SUCCESS",
            title: res.data.msg,
          });
          if (res.data.status == 0){
            //不上课和免单课程 直接跳到详情
            if (requerData.sysPay == 2){
              wx.navigateTo({
                url: '../groupinfo/index?orderCode=' + res.data.data.orderCode,
              });
            }else{
              //发起支付请求
              // self.grouppayment(item, res.data.data.orderCode);
              self.cygroup(res.data.data.orderCode);
            }
          } else if (res.data.status == -2) {
              wx.navigateTo({
                url: '../groupinfo/index?orderCode=' + res.data.data.orderCode,
              });
          } else if (res.data.status == -5){
            // self.grouppayment(item, res.data.data.orderCode);
            //下单
            self.cygroup(res.data.data.orderCode);
          }
        }
      }
    })
  },
  //调用支付
  grouppayment: function (orderinfo, orderCode){
    wx.showLoading();    
    wx.request({
      header: {
        token: config.token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        openId: app.globalData.userInfo.openId,
        fee: orderinfo.payPrice, 
        applyName: "商品支付",
        applyNum: orderinfo.tradeCode
      },
      method: "POST",
      url: config.groupPaymentUrl,
      success: res2 => {
        wx.hideLoading();
        if (res2.data) {
          //调用支付接口
          wx.requestPayment({
            timeStamp: res2.data.timeStamp,
            nonceStr: res2.data.nonceStr,
            package: res2.data.package,
            signType: res2.data.signType,
            paySign: res2.data.paySign,
            success: function (payres) {
              if (payres.errMsg = "requestPayment:ok") {
                //支付成功 记录formId
                // _this.saveFormid(paymentprom.prepay_id);

                wx.navigateTo({
                  url: '../groupinfo/index?orderCode=' + orderCode,
                });
              }
            }
          })
        } else {
          wx.showToast({
            icon: "none",
            title: "支付请求失败",
          })
        }
      }
    });
  },
  //我要参团中 参与拼团
  uscygroup: function(event){
    var index = event.currentTarget.dataset.index;
    var list = this.data.crGrouplist;
    var item = list[index];
    var self = this;
    // console.log(item);
    wx.showModal({
      title: '',
      content: '您确定要支付' + item.ptPrice + '元,参加' + item.subName+'团购吗？',
      cancelText: "不要",
      confirmColor: "#40AFFE",
      success: function(res){
        if(res.confirm){
          self.cygroup(item.orderCode);
        }
      }
    })
  },
  cygroup: function (orderCode){
    wx.showLoading();
    var self = this;
    wx.request({
      header: {
        token: config.token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        orderCode: orderCode,
        openId: app.globalData.userInfo.openId,
        pic: app.globalData.wxInfo.avatarUrl
      },
      method: "POST",
      url: config.cygroupUrl,
      success: res => {
        wx.hideLoading();
        if (res && res.data) {
          if (res.data.status == 0 || res.data.status == -4) {
            wx.showToast({
              icon: "SUCCESS",
              title: res.data.msg,
            });
            self.grouppayment(res.data.data, orderCode);
          } else {
            wx.showToast({
              icon: "none",
              title: res.data.msg,
            })
          }
        }
      }
    })
  },
  showsearch: function(){
    var value = wx.getStorageSync('keywordhistory');
    this.setData({
      showsearch: true,
      keywordhistory: value
    });
  }, 
  cancelssearch: function(){
    this.setData({
      showsearch: false,
      keyword: "输入关键字",
    });
    this.search();
  },
  htssearch: function(event){
    this.setData({
      keyword: event.currentTarget.dataset.keyword
    });
    this.search();
  },
  search: function(keyword){
    this.setData({
      showsearch: false
    });

    this.setData({
      defaultGroup: [],
      crGrouplist: [],
      isnulldata: false,
      pageindex: 0,
      pageindex2: 0,
    });
    this.onReachBottom();
  },
  clearhis: function(){
    wx.setStorageSync('keywordhistory', null);
    this.setData({
      keywordhistory: null
    })
  },
  setkeyword: function (event){
    this.setData({
      keyword: event.detail.value
    })
  },
  searchinput: function(){
    var value = wx.getStorageSync('keywordhistory');
    
    if (value && value.length){
      console.log(value)
      value.push(this.data.keyword);
      
    }else{
      value = [this.data.keyword];
    }
   
    wx.setStorageSync('keywordhistory', value);
    this.setData({
      keywordhistory: value
    })
    this.search();
  },
  //粉丝按钮
  showfxnavbtn: function(){
    this.setData({
      showfxnavbar: !this.data.showfxnavbar
    });
  },
  targetblank: function(event){
    var url = event.currentTarget.dataset.url;
    console.log(url);
    this.setData({
      showfxnavbar: false
    });
    wx.navigateTo({
      url: url
    });
  },
  onShareAppMessage: function (option) {
    
  }
})
